package com.authine.cloudpivot.ext.controller.equipment;

import com.authine.cloudpivot.engine.api.model.organization.UserModel;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectCreatedModel;
import com.authine.cloudpivot.engine.api.model.runtime.WorkItemModel;
import com.authine.cloudpivot.engine.api.model.runtime.WorkflowInstanceModel;
import com.authine.cloudpivot.engine.enums.status.SequenceStatus;
import com.authine.cloudpivot.ext.Utils.CustomSchemaCode;
import com.authine.cloudpivot.ext.service.CloudSqlService;
import com.authine.cloudpivot.web.api.controller.base.BaseController;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @author fengjie
 * @version 1.0.0
 * @ClassName EquipmentMaintenanceController
 * @Description 设备维修
 * @createTime 2023/2/2 8:43
 */
@RestController
@RequestMapping("/public/equipment")
@Slf4j
public class EquipmentMaintenanceController extends BaseController {
    @Autowired
    CloudSqlService sqlService;

    /**
     * 【设备维修记录】审批完成后，数据同步到【设备维修记录 基础表】
     */
    @RequestMapping("finishToEquipmentBase")
    public void finishToOfficeUnitBase1(String bizId) {
        BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject(CustomSchemaCode.EQUIPMENT_MAINTENANCE, bizId);
        // 相关档案明细表
        List<Map<String, Object>> list = (List<Map<String, Object>>) bizObject.get(CustomSchemaCode.MAINTENANCE_DETAIL);

        String approval = getFileBaseInfoWorkFlowApproval(bizObject);
        //
        for (Map<String, Object> map : list) {
            try {
                Map<String, Object> data = fileInfoBaseMap(bizObject, map, approval);
                // 判断是否已存在
                String id = existsBizObject(data, CustomSchemaCode.EQUIPMENT_MAINTENANCE_BA);
                if (StringUtils.isNotEmpty(id)) {
                    data.put("id", id);
                }
                BizObjectCreatedModel model = new BizObjectCreatedModel(CustomSchemaCode.EQUIPMENT_MAINTENANCE_BA, data, false);
                model.setSequenceStatus(SequenceStatus.COMPLETED.name());
                id = getBizObjectFacade().saveBizObject(CustomSchemaCode.adminUserId, model, false);
                log.info("设备维修记录 基础表数据新增成功");
                // 调用存储过程
                callSyncFacilityManageProcess(id);
            } catch (Exception e) {
                log.info("设备维修记录 基础表数据维护失败，报错信息：{}", e.getMessage());
                log.info("设备维修记录 基础表数据操作失败 往来单位代码={}", map.get("functionCode"));
            }
        }
    }

    /**
     * 调用存储过程
     * ------设备维修记录
     * exec   SyncFacilityManage
     */
    private void callSyncFacilityManageProcess(String bizId) {
        if (StringUtils.isEmpty(bizId)) {
            return;
        }
        // 编写sql
        String tableName = getBizObjectFacade().getTableName(CustomSchemaCode.EQUIPMENT_MAINTENANCE_BA);
        StringBuilder sql = new StringBuilder("SELECT * from ")
                .append(tableName).append(" where id ='")
                .append(bizId).append("';");
        // 查询到入参
        Map<String, Object> map = sqlService.getMap(sql.toString());
new StringBuilder().append("kkk");
        log.info("入参map={}", map);

        // 调用存储过程
        String companyCode = MapUtils.getString(map, "companyCode", "");// 公司代码
        String functionName = MapUtils.getString(map, "functionName", "");// 场地代码
        String materialNumber = MapUtils.getString(map, "materialNumber", "");// 物料编码
        String assetsCodeStr = MapUtils.getString(map, "assetsCodeStr", "");// 固定资产编码
        String repairDeptCode = MapUtils.getString(map, "repairDeptCode", "");// 维修部门代码
        String repairPostNumber = MapUtils.getString(map, "repairPostNumber", "");// 维修岗代码
        String statusNum = "";
        String status = MapUtils.getString(map, "status", "");// 维修  (1)   异常  (2)
        if ("维修".equals(status)) {
            statusNum= "1";
        } else if ("异常".equals(status)) {
            statusNum= "2";
        }
        String exceptionDescription = MapUtils.getString(map, "exceptionDescription", "");// 异常说明
        Date createdTime = (Date)map.get("createdTime");;// 报修时间
        Date planTime = (Date)map.get("planTime");// 计划维修时间
        String jobDescription = MapUtils.getString(map, "jobDescription", "");// 工作说明
//        Date time = (Date) map.get("time");// 审批时间

        LocalDateTime time = (LocalDateTime) map.get("time");// 审批时间
//        String enabledTime =  ObjectUtils.isEmpty(enabledTimeTemp) ? "" : enabledTimeTemp.toLocalDate().toString();


        String auditer = MapUtils.getString(map, "auditer", "");// 审批人

        String execSql = String.format("exec [HG_LINK].[hg].[dbo].SyncFacilityManage '%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s'",
                companyCode, functionName, materialNumber, assetsCodeStr, repairDeptCode, repairPostNumber, statusNum, exceptionDescription,createdTime,planTime,jobDescription,time,auditer);
        log.info("\n==========准备调用存储过程:{}", execSql);
        sqlService.execute(CloudSqlService.htEas, execSql);
        log.info("\n=============存储过程执行完成");
    }

    /**
     * 查询审批人,返回  员工号+姓名
     *
     * @param bizObject
     * @return
     */
    private String getFileBaseInfoWorkFlowApproval(BizObjectCreatedModel bizObject) {
        WorkflowInstanceModel instanceModel = getWorkflowInstanceFacade().getByObjectId(bizObject.getId());
        List<WorkItemModel> workItems = getWorkflowInstanceFacade().getWorkItems(instanceModel.getId(), true);
        final String finalActivityCode = "Activity21";
        Optional<WorkItemModel> first = workItems.stream().filter(a -> a.getActivityCode().equals(finalActivityCode)).findFirst();
        String participant = null;
        if (first.isPresent()) {
            participant = first.get().getParticipant();
        }
        if (participant == null) {
            final String finalActivityCode2 = "Activity18";
            Optional<WorkItemModel> second = workItems.stream().filter(a -> a.getActivityCode().equals(finalActivityCode2)).findFirst();
            if (second.isPresent()) {
                WorkItemModel workItemModel = second.get();
                participant = workItemModel.getParticipant();
            }
        }
        if (participant == null) {
            final String finalActivityCode2 = "Activity12";
            Optional<WorkItemModel> second = workItems.stream().filter(a -> a.getActivityCode().equals(finalActivityCode2)).findFirst();
            if (second.isPresent()) {
                WorkItemModel workItemModel = second.get();
                participant = workItemModel.getParticipant();
            }
        }
        if (participant == null) {
            participant = bizObject.getCreater().getId();
        }
        UserModel user = getOrganizationFacade().getUser(participant);
        return new StringBuilder(user.getEmployeeNo()).append("　").append(user.getName()).toString();
    }


    /**
     * 判断是否已存在
     *
     * @return
     */
    private String existsBizObject(Map data, String schemaCode) {

        String tableName = getBizObjectFacade().getTableName(schemaCode);

        StringBuilder sql = new StringBuilder("select id  from ").append(tableName)
                .append(" where companyCode='").append(data.get("companyCode")).append("'")
                .append(" and functionName='").append(data.get("functionName")).append("'")
                .append(" and materialNumber='").append(data.get("materialNumber")).append("'")
                .append(";");
        List<Map<String, Object>> list = sqlService.getList(sql.toString());
        if (CollectionUtils.isNotEmpty(list)) {
            if (list.size() == 1) {
                return list.get(0).get("id").toString();
            } else {
                sql = new StringBuilder("select id  from ").append(tableName)
                        .append(" where companyCode='").append(data.get("companyCode")).append("'")
                        .append(" and functionName='").append(data.get("functionName")).append("'")
                        .append(" and materialNumber='").append(data.get("materialNumber")).append("'")
                        .append(" and assetsCodeStr='").append(data.get("assetsCodeStr")).append("'")
                        .append(";");
                Map<String, Object> map = sqlService.getMap(sql.toString());
                return (String) map.get("id");
            }
        } else {
            return "";
        }
    }

    /**
     * 设置基础表数据
     *
     * @param bizObject 主表数据
     * @param map       子表数据
     * @param auditer   审批人
     * @return
     */
    public static Map<String, Object> fileInfoBaseMap(BizObjectCreatedModel bizObject, Map<String, Object> map, String auditer) {
        // 审批人,审批时间
        map.put("applicant", bizObject.get("applicant"));
        map.put("auditer", auditer);
        map.put("time", new Date());
        map.remove("rowStatus");
        map.remove("id");
        return map;
    }
}
